package com.example.aop;

import com.example.mapper.OperateLogMapper;
import com.example.pojo.OperateLog;
import com.example.utils.CurrentHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Date;

//@Aspect
@Component
public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.example.annoation.OperationLog)")
    public Object logOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

        // 执行方法
        Object result = joinPoint.proceed();

        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;

        /* 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
         获取类名和方法名
        String className = method.getDeclaringClass().getName();
        String methodName = method.getName();*/

        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        StringBuilder params = new StringBuilder();
        for (Object arg : args) {
            params.append(arg).append(", ");
        }
        if (params.length() > 0) {
            params.setLength(params.length() - 2); // 移除最后一个逗号和空格
        }

        // 构造日志对象
        OperateLog log = new OperateLog();
        log.setOperateEmpId(CurrentHolder.getCurrentId()); // 操作人ID
        log.setOperateTime(LocalDateTime.now());// 操作时间
        log.setClassName(joinPoint.getTarget().getClass().getName());// 类名
        log.setMethodName(joinPoint.getSignature().getName());// 方法名
        log.setMethodParams(params.toString());// 方法参数
        log.setReturnValue(result.toString());// 返回值
        log.setCostTime(duration);// 执行时间

        // 插入日志
        operateLogMapper.insert(log);

        return result;
    }
}